package com.hsy.crm.web.utils;

import org.apache.commons.lang3.reflect.FieldUtils;

import java.lang.reflect.Field;

public class PropertyUtils {

    public static Object getProperty(Object bean, String name){
        try {
            return FieldUtils.readField(bean,name,Boolean.TRUE);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    public static String getStringProperty(Object bean, String name){
        Object value = getProperty(bean,name);
        if( value == null ){
            return null;
        }else{
            return value.toString();
        }
    }

    public static void setProperty(Object bean, String name, Object value){
        setProperty(bean,name,value,Boolean.TRUE);
    }

    public static void setProperty(Object bean, String name, Object value,boolean isSureExists){

        if( !isSureExists && !hasProperty(bean,name) ){
            return;
        }

        try {
            FieldUtils.writeField(bean,name,value,Boolean.TRUE);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }





    public static Field getField(Class clazz, String name){
        return FieldUtils.getField(clazz,name,Boolean.TRUE);
    }

    private static boolean hasProperty(Object bean, String name){
        return getField(bean.getClass(),name) != null;
    }
}